package com.duke.framework.redisson.util;

import com.duke.framework.redisson.distributed.locker.DistributedLocker;
import org.redisson.api.RLock;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created duke on 2018/7/27
 */
@Component
public class RedissLockUtil {

    private static DistributedLocker locker;

    public static void setLocker(DistributedLocker distributedLocker) {
        locker = distributedLocker;
    }

    /**
     * 加锁
     *
     * @param lockKey 锁的key值
     * @return RLock
     */
    public static RLock lock(String lockKey) {
        return locker.lock(lockKey);
    }

    /**
     * 释放锁
     *
     * @param lockKey 锁的key值
     */
    public static void unlock(String lockKey) {
        locker.unlock(lockKey);
    }

    /**
     * 释放锁
     *
     * @param lock 锁
     */
    public static void unlock(RLock lock) {
        locker.unlock(lock);
    }

    /**
     * 带超时的锁
     *
     * @param lockKey 锁的key值
     * @param timeout 超时时间   单位：秒
     */
    public static RLock lock(String lockKey, int timeout) {
        return locker.lock(lockKey, timeout);
    }

    /**
     * 带超时的锁
     *
     * @param lockKey 锁的key值
     * @param unit    时间单位
     * @param timeout 超时时间
     */
    public static RLock lock(String lockKey, TimeUnit unit, int timeout) {
        return locker.lock(lockKey, unit, timeout);
    }

    /**
     * 尝试获取锁
     *
     * @param lockKey   锁的key值
     * @param waitTime  最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @return boolean
     */
    public static boolean tryLock(String lockKey, int waitTime, int leaseTime) {
        return locker.tryLock(lockKey, TimeUnit.SECONDS, waitTime, leaseTime);
    }

    /**
     * 尝试获取锁
     *
     * @param lockKey   锁的key值
     * @param unit      时间单位
     * @param waitTime  最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @return boolean
     */
    public static boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        return locker.tryLock(lockKey, unit, waitTime, leaseTime);
    }
}
